| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- import { pick } from "lodash";
- import { NextResponse } from "next/server";
- import { WLEDClient } from "wled-client";
- import automation from "data/automation.json";
- const action = async ({ id, client, on }) => {
- let wled;
- let errors = [];
- try {
- console.log("connect to", client);
- wled = new WLEDClient(client); // setup a connection to the client
- await wled.init(); // init the connection
- } catch (err) {
- console.log("connect error", err.message);
- errors.push({ error: err.message, type: "connect", client: client });
- }
- try {
- console.log("set preset to", id);
- await wled.setPreset(id); // set the preset
- // await wled.setPreset(id); // set it again
- } catch (err) {
- console.log("preset error", err.message);
- errors.push({ error: err.message, type: "preset", client: client, id: id });
- }
- try {
- console.log("set power to", on);
- if (on) await wled.turnOn(); // turn off the lights
- else await wled.turnOff(); // turn off the lights
- } catch (err) {
- console.log("power error", err.message);
- errors.push({ error: err.message, type: "power", client: client, on });
- }
- try {
- await wled.refreshState();
- } catch (err) {
- console.log("state refresh", err.message);
- errors.push({ error: err.message, type: "refreshState", client: client });
- }
- return {
- ...pick(wled?.state || {}, ["on", "brightness", "presetId", "udpSync"]),
- errors
- };
- };
- export async function GET(req, { params }) {
- let promises = [];
- let id = params?.id || null;
- try {
- if (!id) throw new Error("No id specified");
- let clients = (automation?.[id] && Object.keys(automation?.[id])) || [];
- if (!clients) throw new Error("No clients for id", id);
- for (let client of clients) {
- promises.push(action({ id, client, ...automation?.[id]?.[client] }));
- }
- } catch (err) {
- return NextResponse.json({ error: err?.message }, { status: 500 });
- }
- return Promise.allSettled(promises)
- .then((results) => {
- console.log("results", results);
- return NextResponse.json(results?.map((o) => o?.value));
- })
- .catch((err) => {
- return NextResponse.json({ error: err?.message }, { status: 500 });
- });
- }
|